import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const collapsed = ref(false)
  const theme = ref(localStorage.getItem('theme') || 'light')
  const currentProduct = ref('')
  const currentVersion = ref('')
  const products = ref([])

  // 计算属性
  const isDark = computed(() => theme.value === 'dark')
  const themeIcon = computed(() => (isDark.value ? 'Sunny' : 'Moon'))

  // 获取当前产品信息的计算属性
  const getCurrentProductInfo = computed(() => {
    try {
      if (!currentProduct.value || !currentVersion.value) return null
      if (!products.value || !Array.isArray(products.value)) return null

      return products.value.find(p => {
        if (Array.isArray(p)) {
          // 嵌套数组格式: [id, name, version, ...]
          const productId = p[0]?.toString?.() || ''
          const productName = p[1]?.toString?.() || ''
          const version = p[2]?.toString?.() || ''
          return productName === currentProduct.value && version === currentVersion.value
        } else if (typeof p === 'string') {
          // 扁平字符串格式
          return p === currentProduct.value
        } else if (p && typeof p === 'object') {
          // 对象格式: {id, name, version, ...}
          return p.name === currentProduct.value && p.version === currentVersion.value
        }
        return false
      }) || null
    } catch (error) {
      console.error('Error in getCurrentProductInfo computed:', error)
      return null
    }
  })

  // 获取当前产品ID的计算属性
  const getCurrentProductId = computed(() => {
    const info = getCurrentProductInfo.value
    if (info) {
      return typeof info === 'string' ? info : info.id
    }
    return currentProduct.value
  })

  // 获取当前产品名称和版本的显示文本
  const currentProductName = computed(() => {
    const info = getCurrentProductInfo.value
    if (info && typeof info !== 'string') {
      return `${info.name} (${info.version})`
    }
    return currentProduct.value ? `${currentProduct.value}${currentVersion.value ? '/' + currentVersion.value : ''}` : ''
  })

  // 方法
  const setLoading = (value) => {
    loading.value = value
  }

  const toggleSidebar = () => {
    collapsed.value = !collapsed.value
  }

  const setTheme = (newTheme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)

    const html = document.documentElement
    if (newTheme === 'dark') {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }
  }

  const toggleTheme = () => {
    setTheme(isDark.value ? 'light' : 'dark')
  }

  const setCurrentProduct = (productId, version = '') => {
    currentProduct.value = productId
    currentVersion.value = version
    // 保存到localStorage
    localStorage.setItem('currentProduct', productId)
    localStorage.setItem('currentVersion', version)
  }

  const setProducts = (productList) => {
    products.value = productList
    if (!currentProduct.value && productList.length > 0) {
      const savedProduct = localStorage.getItem('currentProduct')
      const savedVersion = localStorage.getItem('currentVersion') || ''

      // 处理两种格式的产品数据
      let firstProduct, firstVersion
      if (typeof productList[0] === 'string') {
        // 数组格式: ["id", "name", "version", ...] - 但这种情况应该来自products API
        firstProduct = productList[0]
        firstVersion = ''
      } else {
        // 对象格式: {id, name, version, ...}
        firstProduct = productList[0].name || productList[0].id
        firstVersion = productList[0].version || ''
      }

      const productExists = productList.some(p => {
        const productName = typeof p === 'string' ? p : p.name
        const productVersion = typeof p === 'string' ? '' : p.version
        return productName === savedProduct && productVersion === savedVersion
      })

      // 优先使用保存的产品信息，否则选择第一个产品
      if (productExists && savedProduct) {
        setCurrentProduct(savedProduct, savedVersion)
      } else {
        setCurrentProduct(firstProduct, firstVersion)
      }
      console.log('Auto-selected product:', currentProduct.value, currentVersion.value)
    }
  }

  // 设置产品和版本的便捷方法
  const setCurrentProductInfo = (productInfo) => {
    if (typeof productInfo === 'string') {
      // 如果是字符串，直接设置为产品名
      setCurrentProduct(productInfo, '')
    } else if (productInfo && productInfo.name) {
      // 如果是对象，设置name和version
      setCurrentProduct(productInfo.name, productInfo.version || '')
    }
  }

  // 初始化
  const initialize = async () => {
    setLoading(true)
    try {
      // 这里可以加载初始数据
      setTheme(theme.value)
    } catch (error) {
      console.error('Failed to initialize app:', error)
    } finally {
      setLoading(false)
    }
  }

  return {
    // 状态
    loading,
    collapsed,
    theme,
    currentProduct,
    currentVersion,
    products,

    // 计算属性
    isDark,
    themeIcon,
    getCurrentProductInfo,
    getCurrentProductId,
    currentProductName,

    // 方法
    setLoading,
    toggleSidebar,
    setTheme,
    toggleTheme,
    setCurrentProduct,
    setCurrentProductInfo,
    setProducts,
    initialize
  }
})